<template>
    <ContentWrap>
        <div class="flex justify-between">
            <div class="">
                <el-select v-model="state.searchData.companyValue" clearable filterable class="m-2" placeholder="请选择所属公司"
                    style="width: 200px;">
                    <el-option v-for="item in state.optionsTenantData" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
                <el-select v-model="state.searchData.jobValue" clearable class="m-2" placeholder="请选择职位状态"
                    style="width: 200px;">
                    <el-option v-for="item in state.options2" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <ElInput v-model="state.searchData.keywords" clearable style="width: 266px;height: 32px;margin-right: 10px;"
                    placeholder="请输入职位名称" :prefix-icon="Search" />
                <ElButton type="primary" :icon="Search" @click="onSearch">
                    {{ t('common.query') }}
                </ElButton>
                <ElButton :icon="Refresh" @click="onReset">
                    {{ t('common.reset') }}
                </ElButton>
                <ElButton type="primary" @click="passFun">
                    一键审核通过
                </ElButton>
                <ElButton type="danger" @click="noPassFun">
                    一键审核未通过
                </ElButton>
            </div>
        </div>
        <div class="" style="margin-top: 25px;">
            <Table v-model:pageSize="pageSize" v-model:currentPage="currentPage" :columns="allSchemas.tableColumns"
                :data="dataList" :loading="loading" :pagination="{ total: total }" @register="tableRegister"
                :headerCellStyle="headerCellStyle" :rowStyle="rowStyle" />
        </div>
    </ContentWrap>
    <Dialog v-model="dialogVisible1" title="职位详情" width="1200" style="overflow: auto;" :before-close="beforeClose">
        <JobDetail :data="state.JobDetail" />
    </Dialog>
</template>
    
<script setup lang="tsx">
import { JobDetail } from "./components/index"
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { Search, Refresh } from '@element-plus/icons-vue'
import { Dialog } from '@/components/Dialog'
import { useEmitt } from '@/hooks/event/useEmitt'
import { ElButton, ElInput, ElMessage, ElMessageBox,ElSwitch } from 'element-plus'
// import { propTypes } from '@/utils/propTypes'
import { useI18n } from '@/hooks/web/useI18n'
import { ContentWrap } from '@/components/ContentWrap'
import { ref, reactive, unref } from "vue"
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { getPositionListApi, editPositionApi, editPositionApis, getPositionDetailApi } from "@/api/job/index"
import { formatToDateTime } from "@/utils/dateUtil"
import { getTenantListApi } from "@/api/business/index"
const { t } = useI18n()
const dialogVisible1 = ref(false)//定义职位详情弹框
const state = reactive({
    searchData: {
        companyValue: "",
        jobValue: "",
        keywords: ""
    },//搜索参数
    options1: [] as any,//所属公司下拉框
    options2: [
        { label: "未通过", value: 0 },
        { label: "待审核", value: 1 },
        { label: "已通过", value: 2 },
    ] as any,//职位状态下拉框
    react: true,//分页刷新
    optionsTenantData: [] as any,
    JobDetail: {} as any,
})
// 表格基本信息
const crudSchemas = reactive<CrudSchema[]>([
    {
        field: 'selection',
        type: 'selection'
    },
    {
        field: 'positionName',
        label: t('职位名称'),
        search: {
            component: 'Input'
        },
        form: {
            component: 'Input',
            colProps: {
                span: 24
            }
        },
        detail: {
            span: 24
        }
    },
    {
        field: 'tenantName',
        label: t('所属公司'),
        search: {
            hidden: true
        }
    },
    {
        field: 'author',
        label: t('薪资范围'),
        search: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <div>{data[0].row.salaryStart ? data[0].row.salaryStart : ''}-{data[0].row.salaryEnd ? data[0].row.salaryEnd : ''}{data[0].row.salaryUnit ? data[0].row.salaryUnit : ''}
                                {data[0].row.salaryRange ? `*` + data[0].row.salaryRange : ''}</div>
                        </>
                    )
                }
            }
        }
    },
    {
        field: 'recruitmentNumber',
        label: t('招聘人数'),
        search: {
            hidden: true
        }
    },
    {
        field: 'status',
        label: t('职位发布状态'),
        search: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <div>{data[0].row.status == 0 ? "未通过" : data[0].row.status == 1 ? '待审核' : data[0].row.status == 2 ? "已通过" : "已关闭"}</div>
                        </>
                    )
                }
            }
        }
    },
    {
        field: 'delFlag',
        label: t('职位存在状态'),
        search: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <div>{data[0].row.delFlag == 0 ? "未删除" : data[0].row.delFlag == 2 ? '已删除' : ""}</div>
                        </>
                    )
                }
            }
        }
    },
    {
        field: 'reviewTags',
        label: t('系统自动审核'),
    },
    {
        field: 'createTime',
        label: t('发布日期'),
        search: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <div >{data[0].row.createTime.slice(0,16)}</div>
                        </>
                    )
                }
            }
        }
    },
    {
        field: 'isAd',
        label: t('职位推荐'),
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <div ><ElSwitch style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-value="1" inactive-value="0" v-model={data[0].row.isAd} before-change={() => switchClick(data[0].row)} /></div>
                        </>
                    )
                }
            }
        }
    },
    {
        field: 'recruitmentDeadline',
        label: t('截止日期'),
        search: {
            hidden: true
        }
    },
    {
        field: 'action',
        width: '260px',
        label: t('tableDemo.action'),
        search: {
            hidden: true
        },
        form: {
            hidden: true
        },
        detail: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <ElButton link type="primary" onClick={() => action(data[0].row)}>
                                {t('职位详情')}
                            </ElButton>
                            <ElButton link type="primary" v-if={data[0].row.status == 0} onClick={() => receat(data[0].row)}>
                                {t('审核通过')}
                            </ElButton>
                            <ElButton link type="danger" onClick={() => delData(data[0].row)}>
                                {t('审核未通过')}
                            </ElButton>

                        </>
                    )
                }
            }
        }
    }
])
const { tableRegister, tableState, tableMethods } = useTable({
    fetchDataApi: async () => {
        const { currentPage, pageSize } = tableState
        const res: any = await getPositionListApi({
            pageNum: state.react ? 1 : unref(currentPage),
            pageSize: unref(pageSize),
            positionName: state.searchData.keywords,
            tenantId: state.searchData.companyValue,
            status: state.searchData.jobValue
        })
        console.log("审核职位列表",res);
        res.rows.forEach(elements => {
            if (elements.status == 0) {
                elements.statusBoolean = true
            } else {
                elements.statusBoolean = false
            }
            state.optionsTenantData.forEach(element => {
                if (elements.tenantId == element.value) {
                    elements.tenantName = element.label
                }

            })
        })
        let arrays = res.rows
        arrays.forEach(element => { 
            element.isAd = element.isAd.toString()
        })
        state.react = false
        return {
            list: arrays,
            total: res.total
        }
    }
})

// 表格头部信息
const headerCellStyle: any = {
    "background": "#F2F6FC",
    "height": "48px"
}
// 
const rowStyle: any = {
    "height": "48px"
}
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods
useEmitt({
    name: 'getList',
    callback: (type: string) => {
        if (type === 'add') {
            currentPage.value = 1
        }
        getList()
    }
})
const { allSchemas } = useCrudSchemas(crudSchemas)
const switchClick = (rows) => {
    let strings = rows.isAd == 0 ? "确认首页置顶该职位？" : "取消首页置顶该职位？"
    ElMessageBox.confirm(
        `${strings}`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            let params =[ {
                id: rows.id,
                isAd: rows.isAd == 0 ? 1 : 0
            }]
            editPositionApis(params).then((res: any) => {
                getList()
                ElMessage({
                    type: 'success',
                    message: `${res.msg}`,
                })
            }).catch((res: any) => {
                ElMessage({
                    type: 'error',
                    message: `${res.msg}`,
                })
            })

        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}
const beforeClose=()=>{
    dialogVisible1.value=false
    getList()
}
const action = (row: any) => {
    console.log("职位详情", row);
    // if (row.delFlag == 2) {
    //     ElMessage({
    //         type: 'warning',
    //         message: `该职位已被删除,无法查看详情信息！`,
    //     })
    //     return
    // }
    getPositionDetailApi_(row.id)
}
const delData = (row: any) => {
    console.log("审核未通过", row);
    ElMessageBox.prompt('审核未通过原因', '职位审核未通过？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern:,
        draggable: true,
        inputPlaceholder: "请输入审核未通过原因",
        inputErrorMessage: '请输入审核未通过原因',
    })
        .then(({ value }) => {
            let params = {
                id: row.id,
                status: 0,
                resultComment: value,
            }
            editPositionApi(params).then((res: any) => {
                getList()
                ElMessage({
                    type: 'success',
                    message: `${res.msg}`,
                })
            }).catch((res: any) => {
                ElMessage({
                    type: 'error',
                    message: `${res.msg}`,
                })
            })

        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })

}
const receat = (row: any) => {
    console.log("审核通过", row);
    ElMessageBox.confirm('职位审核通过后，该职位将发布在官网', '请确认该职位审核通过？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern:,
        draggable: true,
    })
        .then(() => {
            let params = {
                id: row.id,
                status: 2
            }
            editPositionApi(params).then((res: any) => {
                getList()
                ElMessage({
                    type: 'success',
                    message: `${res.msg}`,
                })
            }).catch((res: any) => {
                ElMessage({
                    type: 'error',
                    message: `${res.msg}`,
                })
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })


}
// 查询
const onSearch = () => {
    console.log("查询");
    state.react = true
    getList()
}
// 重置
const onReset = () => {
    console.log("重置");
    state.searchData.companyValue = ""
    state.searchData.keywords = ""
    state.searchData.jobValue = ""
    state.react = true
    getList()
}
// 一键通过
const passFun = async () => {
    const elTableRef = await getElTableExpose()
    const selections = elTableRef?.getSelectionRows()
    console.log(selections)
    if (selections.length == 0) {
        ElMessage({
            type: 'warning',
            message: `请选择职位！`,
        })
        return
    }
    ElMessageBox.confirm('职位审核通过后，该职位将发布在官网', '请确认该职位审核通过？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern:,
        draggable: true,
    })
        .then(() => {
            let arrays = [] as any
            selections.forEach((el, key) => {
                let params = {
                    id: el.id,
                    status: 2,
                }
                arrays.push(params)
            })
            editPositionApis(arrays).then((res: any) => {
                getList()
                ElMessage({
                    type: 'success',
                    message: `${res.msg}`,
                })
            }).catch((res: any) => {
                ElMessage({
                    type: 'error',
                    message: `${res.msg}`,
                })
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })

}
// 一键拒绝
const noPassFun = async () => {
    const elTableRef = await getElTableExpose()
    const selections = elTableRef?.getSelectionRows()
    console.log(selections)
    if (selections.length == 0) {
        ElMessage({
            type: 'warning',
            message: `请选择职位！`,
        })
        return
    }
    ElMessageBox.prompt('审核未通过原因', '职位审核未通过？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern:,
        draggable: true,
        inputPlaceholder: "请输入审核未通过原因",
        inputErrorMessage: '请输入审核未通过原因',
    })
        .then(({ value }) => {
            let arrays = [] as any
            selections.forEach((el, key) => {
                let params = {
                    id: el.id,
                    status: 0,
                    resultComment: value,
                }
                arrays.push(params)
            })
            editPositionApis(arrays).then((res: any) => {
                getList()
                ElMessage({
                    type: 'success',
                    message: `${res.msg}`,
                })
            }).catch((res: any) => {
                ElMessage({
                    type: 'error',
                    message: `${res.msg}`,
                })
            })

        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}
// api区域---------------------------------------------------------------------------
const getTenantListApi_ = async () => {
    getTenantListApi({ pageNum: 1, pageSize: 10000 }).then((res: any) => {
        console.log("租户", res);
        state.optionsTenantData = []
        res.rows.forEach(element => {
            let obj = {
                label: element.companyName,
                value: element.tenantId
            }
            state.optionsTenantData.push(obj)
        });
        getList()
    })
}
getTenantListApi_()
const getPositionDetailApi_ = async (params) => {
    getPositionDetailApi(params).then((res: any) => {
        console.log("详情", res);
        state.JobDetail = res.data
        dialogVisible1.value = true

    })
}
</script>
    
<style lang="less" scoped></style>